# encoding=utf-8
# author: liguofa 
# date: 2020-10-22 
# time: 21:04
# IDE: PyCharm

from django.shortcuts import render,HttpResponse,redirect
import random
from django.http import JsonResponse
from django.contrib import auth


def get_random_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))


def get_valid_code_img(request):

    #方式1：
    # with open("timg.jpg","rb") as f:
    #
    #     data=f.read()

    #方式2：pip install pillow,先生成图片放在磁盘中，在读取，速度慢。
    # from PIL import Image
    # img=Image.new("RGB",(270,36),color=get_random_color())
    #
    # with open("validCode.png","wb") as f:
    #     img.save(f,'png')
    #
    # with open("validCode.png", "rb") as f:
    #
    #    data=f.read()
    #


    # #方式3：缓存机制
    # from PIL import Image
    # from io import BytesIO #内存管理工具
    # img = Image.new("RGB", (270, 36), color=get_random_color())
    #
    # f=BytesIO()
    # img.save(f,'png')
    # data=f.getvalue()

    # 方式4：缓存机制
    from PIL import Image,ImageDraw,ImageFont
    from io import BytesIO  # 内存管理工具
    img = Image.new("RGB", (270, 36), color=get_random_color())

    draw=ImageDraw.Draw(img)
    font=ImageFont.truetype("static/font/demo.ttf",size=25)

    #生成随机验证码
    valid_code_str=""
    for i in range(5):
        random_num=str(random.randint(0,9))
        random_low_alpha=chr(random.randint(95,122))
        random_upper_alpha = chr(random.randint(65, 90))
        random_char=random.choice([random_num,random_low_alpha,random_upper_alpha])
        draw.text((i*50+20,4),random_char,get_random_color(),font=font)#画文字

        #保存验证码
        valid_code_str+=random_char


    print(valid_code_str)

    request.session["valid_code_str"]=valid_code_str

    """
    1.shengcheng sui ji zi fu chuan 
    2.set COOKIE{"sessionid":sui ji zi fu chuan}
    3.django-session cun chu
        session-key session-data
    eg: zui ji zi fu chuan {"valid_code_str":"12345"}
    """

    #验证码的噪点，防止爬虫脚本
    # width=270
    # height=36
    # for i in range(10):
    #     x1=random.randint(0,width)
    #     x2 = random.randint(0, width)
    #     y1 = random.randint(0, height)
    #     y2 = random.randint(0, height)
    #     #draw.line()#画线
    #     draw.line((x1,y1,x2,y2),fill=get_random_color())
    #
    # for i in range(100):
    #     # draw.point()#画点
    #     draw.point([random.randint(0, width),random.randint(0, height)],fill=get_random_color())
    #     x=random.randint(0,width)
    #     y=random.randint(0, height)
    #     draw.arc((x,y,x+4,y+4,),0,90,fill=get_random_color())

    f = BytesIO()
    img.save(f, 'png')
    data = f.getvalue()

    return data